# -*- coding: utf-8 -*-
# File : operator_db_create.py
# Author: taoyahui
# Date : 2021/5/21
import sys
import pymysql
import mysql_util
import configparser
cf = configparser.ConfigParser()
cf.read("config.ini")

secs = cf.sections()
print(secs)
host = cf.get("Mysql-Database", "host")
port = cf.get("Mysql-Database", "port")
user = cf.get("Mysql-Database", "user")
password = cf.get("Mysql-Database", "password")
db = cf.get("Mysql-Database", "db")

def sync_mysql_data(file):
    with open(file, "r") as f:  # 打开文件
        data = f.read()
        lines = data.splitlines()
        sql_data = ''
        for line in lines:
            if len(line) == 0:
                continue
            elif line.startswith("--"):
                continue
            else:
                sql_data += line
        sql_list = sql_data.split(';')[:-1]
        sql_list = [x.replace('\n', ' ') if '\n' in x else x for x in sql_list]
    conn = mysql_util.get_conn()
    cur = conn.cursor()
    for sql_item in sql_list:
        cur.execute(sql_item)
    mysql_util.release(conn, cur)


def create_database():
    sql = "CREATE DATABASE IF NOT EXISTS operator;"
    conn = pymysql.connect(host=host, port=int(port), user=user, passwd=password, db='sys',
                           charset='utf8mb4')
    cur = conn.cursor()
    cur.execute(sql)
    mysql_util.release(conn, cur)


if __name__ == '__main__':
    if sys.argv.__len__() > 1:
        # print(sys.argv[1])
        print("** Start create Database! **")
        create_database()
        sync_mysql_data(sys.argv[1])
        print("** Database is created ! **")
